package demo;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LRU缓存机制
 */
class Solution3 {
	int cap;
	LinkedHashMap<Integer, Integer> linkedHashMap = null;
	public Solution3(int capacity) {
		this.cap = capacity;
		linkedHashMap = new LinkedHashMap<>();
	}

	public int get(int key) {
		if (linkedHashMap.containsKey(key)) {
			int oldValue = linkedHashMap.get(key);
			linkedHashMap.remove(key);
			linkedHashMap.put(key, oldValue);
		}
		return -1;
	}

	public void put(int key, int value) {
		if (linkedHashMap.containsKey(key)) {
			linkedHashMap.remove(key);
		} else if (linkedHashMap.size() == cap) {
			Iterator<Integer> iterator = linkedHashMap.keySet().iterator();
			iterator.next();
			iterator.remove();
		}
		linkedHashMap.put(key, value);
	}
}

